#!/usr/bin/python3
import glob, os
from .Base_Plugin import Base_Plugin


def get_short_name(plugin: Base_Plugin) -> str:
    """
    获取模块短名称
    """
    return plugin.__module__.split(".")[1]


def get_all_subclasses(directory):
    """
    获取指定文件夹下的所有插件脚本，返回[文件夹.脚本名]形式的路径数组
    """
    python_files = glob.glob(os.path.join(directory, "*.py"))
    new_python_files = list()
    for f in python_files:
        if not os.path.basename(f) == os.path.basename(__file__):
            item = ".".join([c for c in f.split("\\")])
            item = item.replace(".py", "").replace("./", "")
            new_python_files.append(item)
    return new_python_files


def plugins(context) -> list[Base_Plugin]:
    all_plugins = list(context["plugins"])
    ignore_plugins = list(context["ignore_plugins"])
    mounted_plugins = set(all_plugins) - set(ignore_plugins)

    _sub_class_names = get_all_subclasses("./plugins")
    for _sub_classe_name in _sub_class_names:
        if _sub_classe_name.split(".")[1] in all_plugins:
            __import__(_sub_classe_name)

    sub_classes = Base_Plugin.__subclasses__()
    plugin_list = list()
    for sub_class in sub_classes:
        plugin = sub_class(context)
        plugin.enable = get_short_name(plugin) not in ignore_plugins
        plugin_list.append(plugin)
    plugin_list = sorted(
        plugin_list,
        key=lambda plugin: all_plugins.index(get_short_name(plugin)),
    )
    for _p in plugin_list:
        _p.print(f"""已挂载.\n""")
    return plugin_list
